package com.hj.security.ui;

import java.util.List;

import com.hj.security.R;
import com.hj.security.domain.ContactInfo;
import com.hj.security.engine.ContactInfoService;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SelectContactActivity extends Activity{

	private ListView lv_select_contact;
	private ContactInfoService contactInfoService;
	private List<ContactInfo> infos;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_contact);
		lv_select_contact = (ListView) findViewById(R.id.lv_select_contact);
		contactInfoService = new ContactInfoService(this);
		infos = contactInfoService.getContactInfos();
		lv_select_contact.setAdapter(new SelectContactAdapt());
		
		lv_select_contact.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent data = getIntent();
				data.putExtra("name", infos.get(position).getName());
				data.putExtra("phone", infos.get(position).getPhone());
				setResult(0, data);
				finish();
			}
		});
	}
	class SelectContactAdapt extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return infos.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			if(convertView==null){
				view = View.inflate(SelectContactActivity.this, R.layout.contact_item, null);
				TextView tv_contact_name = (TextView) view.findViewById(R.id.tv_contact_name);
				TextView tv_contact_number = (TextView) view.findViewById(R.id.tv_contact_number);
				tv_contact_name.setText(infos.get(position).getName());
				tv_contact_number.setText(infos.get(position).getPhone());
			}else{
				view = convertView;
				TextView tv_contact_name = (TextView) view.findViewById(R.id.tv_contact_name);
				TextView tv_contact_number = (TextView) view.findViewById(R.id.tv_contact_number);
				tv_contact_name.setText(infos.get(position).getName());
				tv_contact_number.setText(infos.get(position).getPhone());
			}
			return view;
		}
		
	}
}
